#!/bin/bash
# menu

# base_dir=$(cd `dirname $0`;pwd)

# 字体库下载地址：http://www.jave.de/figlet/fonts.html
# figlet -f fonts/figletfonts40/fonts/isometric1 menu
# figlet -f fonts/figletfonts40/fonts/jacky menu
# figlet -f fonts/figletfonts40/fonts/modular menu

print_ascii_logo0() {
cat << "LOGO"
      ___           ___           ___           ___
     /\__\         /\  \         /\__\         /\__\
    /::|  |       /::\  \       /::|  |       /:/  /
   /:|:|  |      /:/\:\  \     /:|:|  |      /:/  /
  /:/|:|__|__   /::\~\:\  \   /:/|:|  |__   /:/  /  ___
 /:/ |::::\__\ /:/\:\ \:\__\ /:/ |:| /\__\ /:/__/  /\__\
 \/__/~~/:/  / \:\~\:\ \/__/ \/__|:|/:/  / \:\  \ /:/  /
       /:/  /   \:\ \:\__\       |:/:/  /   \:\  /:/  /
      /:/  /     \:\ \/__/       |::/  /     \:\/:/  /
     /:/  /       \:\__\         /:/  /       \::/  /
     \/__/         \/__/         \/__/         \/__/
LOGO
}

print_ascii_logo1() {
cat << "LOGO"
   __    __      _____      __      _   __    __
   \ \  / /     / ___/     /  \    / )  ) )  ( (
   () \/ ()    ( (__      / /\ \  / /  ( (    ) )
   / _  _ \     ) __)     ) ) ) ) ) )   ) )  ( (
  / / \/ \ \   ( (       ( ( ( ( ( (   ( (    ) )
 /_/      \_\   \ \___   / /  \ \/ /    ) \__/ (
(/          \)   \____\ (_/    \__/     \______/
LOGO
}

print_ascii_logo2() {
cat << "LOGO"
 __   __  _______  __    _  __   __
|  |_|  ||       ||  |  | ||  | |  |
|       ||    ___||   |_| ||  | |  |
|       ||   |___ |       ||  |_|  |
|       ||    ___||  _    ||       |
| ||_|| ||   |___ | | |   ||       |
|_|   |_||_______||_|  |__||_______|
LOGO
}

print_logo() {
	local logo_mappings=(print_ascii_logo0 print_ascii_logo1 print_ascii_logo2)

	local color=$((RANDOM % 6 + 1))
	echo -e "\033[3${color}m"

	local index=$((RANDOM % 3))
	${logo_mappings[$index]}
	echo -e "\033[0m"
}

is_number() {
	local str=`echo $1 | grep -E '^[0-9][0-9]*$'`
	if [ -n "$str" ]; then
		return 0
	fi
	return 1
}

check_exit() {
	local exit_mappings=(q quit exit)
	for item in ${exit_mappings[*]}; do
		if [ "$item" == "$1" ]; then
			echo "exit."
			exit
		fi
	done
}

prefix="--->"

# arg1: var name
# other args: menu item
menu() {
	local var="$1" # var name
	shift

	local args=($*) # array

	while true; do
		# clear
		print_logo
		
		local index=1
		for item in ${args[*]}; do
			echo -n $prefix
			echo " ${index}) ${item}"
			index=$(($index + 1))
		done
		echo -n $prefix
		echo " quit(q)"

		local length=$(($index - 1))

		# Read user input
		read -p "Please input index: " name
		if [ -n "$name" ]; then
			check_exit $name
			# Is number?
			is_number $name
			if [ $? -ne 0 ]; then
				continue
			fi
			# Out of bound?
			if [ $name -le 0 -o $name -gt $length ]; then
				continue
			fi
			# Translate number to menu item name
			index=$(($name-1))
			local val=${args[$index]}
			eval "$var=$val"
			break
		fi
	done
}

# test code.
# menu option mysql redis mongodb
# echo $option
